package com.liwei.lwmail.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.liwei.common.constant.OrderConstant;
import com.liwei.common.to.SkuHasStockVo;
import com.liwei.common.to.mq.OrderTo;
import com.liwei.common.utils.R;
import com.liwei.common.vo.MemberResponseVo;
import com.liwei.lwmail.order.entity.OrderItemEntity;
import com.liwei.lwmail.order.enume.OrderStatusEnum;
import com.liwei.lwmail.order.feign.ProductFeignService;
import com.liwei.lwmail.order.feign.WareFeignService;
import com.liwei.lwmail.order.interceptor.LoginUserInterceptor;
import com.liwei.lwmail.order.feign.CartFeignService;
import com.liwei.lwmail.order.feign.MemberFeignService;
import com.liwei.lwmail.order.service.OrderItemService;
import com.liwei.lwmail.order.to.OrderCreateTo;
import com.liwei.lwmail.order.vo.*;
import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwei.common.utils.PageUtils;
import com.liwei.common.utils.Query;

import com.liwei.lwmail.order.dao.OrderDao;
import com.liwei.lwmail.order.entity.OrderEntity;
import com.liwei.lwmail.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.threadLocal.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            //获取主线程的请求信息
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1、远程查询所有的收货地址列表
            List<MemberAddressVo> addresses = memberFeignService.getAddress(memberResponseVo.getId());
            orderConfirmVo.setAddresses(addresses);
        }, executor);

        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            //获取主线程的请求信息
            RequestContextHolder.setRequestAttributes(requestAttributes);
            ///2、远程查询购物车中的选中项
            List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
            orderConfirmVo.setItems(userCartItems);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIds);
            if (r.getCode() == 0){
                List<SkuHasStockVo> data = r.getData(new TypeReference<List<SkuHasStockVo>>() {});
                if (data != null){
                    Map<Long, Boolean> collect = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                    orderConfirmVo.setHasStock(collect);
                }
            }
        },executor);

        //4、查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //TODO 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX+memberResponseVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        //6、其他数据自动计算

        CompletableFuture.allOf(future1,future2).get();

        return orderConfirmVo;
    }

//    @GlobalTransactional
    @Transactional
    @Override
    public OrderSubmitRespVo subOrder(OrderSubmitVo vo) {
        submitVoThreadLocal.set(vo);
        OrderSubmitRespVo respVo = new OrderSubmitRespVo();
        respVo.setCode(0);
        //获取当前用户
        MemberResponseVo memberResponseVo = LoginUserInterceptor.threadLocal.get();
        //1、验证令牌
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
            //保证对比和删除token为一个原子操作
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken);
        if (result == 1L){
            //验证并删除token成功
            //1、创建订单
            OrderCreateTo order = createOrder();
            //2、验价
            BigDecimal payAmount = order.getOrderEntity().getPayAmount();
            BigDecimal pay = vo.getPay();
            if (Math.abs((pay.subtract(payAmount)).doubleValue()) < 0.01){
                //保存订单
                saveOrder(order);
                //库存锁定
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrderEntity().getOrderSn());
                List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());

                wareSkuLockVo.setOrderItems(collect);
                //远程锁定库存
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0){
                    //成功
                    //int i = 10/0;
                    respVo.setOrderEntity(order.getOrderEntity());
                    //订单创建成功，发送消息给MQ
                    rabbitTemplate.convertAndSend("order.event.exchange","order.create.order",order.getOrderEntity());
                    return respVo;
                }else {
//                    throw new NoStockException(1L);
                    respVo.setCode(3);
                }
            }else {
                respVo.setCode(2);
            }
        }else {
            //失败
            respVo.setCode(1);
        }
        return respVo;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    /**
     * 关闭订单
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity entity = getById(orderEntity.getId());
        if (entity.getStatus()  == OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            updateById(update);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity,orderTo);
            //关单后，给MQ发一个消息
            try{
                rabbitTemplate.convertAndSend("order.event.exchange","order.release.other",orderTo);
            }catch (Exception e){
                //
            }
        }
    }

    private void saveOrder(OrderCreateTo order) {
        //保存订单
        OrderEntity orderEntity = order.getOrderEntity();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        //保存订单项
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }

    private OrderCreateTo createOrder(){
        OrderCreateTo to = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //2、生成订单
        OrderEntity orderEntity = buildOrder(orderSn);
        to.setOrderEntity(orderEntity);
        //3、订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        to.setOrderItems(orderItemEntities);
        //4、计算价格
        computePrice(orderEntity, orderItemEntities);

        return to;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        Integer integrations = 0;
        Integer growth = 0;
        //订单总额
        for (OrderItemEntity entity : orderItemEntities) {
            //累计
            total = total.add(entity.getRealAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            growth += entity.getGiftGrowth();
            integrations += entity.getGiftIntegration();
        }
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);

        orderEntity.setIntegration(integrations);
        orderEntity.setGrowth(growth);
        orderEntity.setDeleteStatus(0);
    }


    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(LoginUserInterceptor.threadLocal.get().getId());
        orderEntity.setCreateTime(new Date());
        orderEntity.setMemberUsername(LoginUserInterceptor.threadLocal.get().getNickname());
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        //2、获取收货信息
        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = r.getData(new TypeReference<FareVo>() {});

        orderEntity.setFreightAmount(fareVo.getFare());//运费
        orderEntity.setReceiverCity(fareVo.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareVo.getAddress().getName());
        orderEntity.setReceiverPhone(fareVo.getAddress().getPhone());
        orderEntity.setReceiverProvince(fareVo.getAddress().getProvince());
        orderEntity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        orderEntity.setReceiverRegion(fareVo.getAddress().getRegion());

        //订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);


        return orderEntity;
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> orderItems = cartFeignService.getUserCartItems();
        if (orderItems != null){
            List<OrderItemEntity> collect = orderItems.stream().map(item -> {
                OrderItemEntity orderItemEntity = buildOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息
        //2、spu信息
        Long skuId = item.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfo = r.getData(new TypeReference<SpuInfoVo>() {});
        orderItemEntity.setSpuId(spuInfo.getId());
        orderItemEntity.setSpuName(spuInfo.getSpuName());
        //根据brandId查询品牌名
        Long brandId = spuInfo.getBrandId();
        R info = productFeignService.info(brandId);
        BrandVo brand = info.getData("brand", new TypeReference<BrandVo>() {});
        orderItemEntity.setSpuBrand(brand.getName());
        orderItemEntity.setCategoryId(spuInfo.getCatalogId());
        //3、sku信息
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuQuantity(item.getCount());
        orderItemEntity.setSkuPic(item.getDefaultImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(item.getSaleAttr(),";"));
        //4、优惠信息
        //5、积分信息
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        //6、价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //订单项的实际金额
        BigDecimal originPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal finalPrice = originPrice.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(finalPrice);

        return orderItemEntity;
    }

}